package com.commodity.servlet;

import com.commodity.Service.CommodityService;
import com.commodity.Service.commodityServiceImp.CommodityServiceImp;
import com.commodity.entity.Commodity;
import com.commodity.entity.CommoditySearchBean;
import com.commodity.utils.BeanFactory;
import com.commodity.utils.FormatMatch;
import com.commodity.utils.PaginateInfo;
import com.commodity.utils.ServletUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

@WebServlet("/commodity/*")
public class CommodityServlet extends HttpServlet {
    private final CommodityService commodityService = BeanFactory.getInstance(CommodityServiceImp.class);

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String action = req.getPathInfo();
        String method = req.getMethod().toLowerCase();
        System.out.println(action + " " + method);
        if ("/list".equals(action)) {
            if ("get".equals(method)) {

                req.getRequestDispatcher("/WEB-INF/jsp/commodity/list.jsp").forward(req, resp);
            } else {
                list(req, resp);
            }
        } else if ("/add".equals(action)) {
            if ("get".equals(method)) {
                String error = (String)req.getSession().getAttribute("error");
                HttpSession session = req.getSession();
                String success = (String) session.getAttribute("success");
                if (StringUtils.hasText(success)){
                    req.setAttribute("success",success);
                    session.removeAttribute("success");
                }else if(StringUtils.hasText(error)){
                    req.setAttribute("error",error);
                    req.getSession().removeAttribute("error");
                    Commodity commodity = (Commodity) req.getSession().getAttribute("commodity");
                    req.setAttribute("commodity",commodity);
                    req.getSession().removeAttribute("commodity");
                }
                req.getRequestDispatcher("/WEB-INF/jsp/commodity/add.jsp").forward(req, resp);
            } else {
                save(req, resp);
            }
        } else if ("/delete".equals(action)) {
            delete(req,resp);
        }else if ("/edit".equals(action)){
            if ("get".equals(method)){
                String id = req.getParameter("id");
                System.out.println(id);
                HttpSession session = req.getSession();
                String success = (String) session.getAttribute("success");
                if (StringUtils.hasText(success)){
                    req.setAttribute("success",success);
                    session.removeAttribute("success");
                }else if (StringUtils.hasText(id)){
                    Commodity commodity = commodityService.findById(Integer.valueOf(id));
                    System.out.println(commodity);
                    if (commodity == null){
                        req.setAttribute("error","要修改的学生不存在");
                    }else{
                        req.setAttribute("commodity",commodity);
                    }
                }else{
                    req.setAttribute("error","未提供要删除的商品主键");
                }
                System.out.println(id);
                req.setAttribute("id",id);
                req.getRequestDispatcher("/WEB-INF/jsp/commodity/edit.jsp").forward(req,resp);
            }else{
                edit(req,resp);
            }
        }
    }

    private void edit(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        System.out.println(id);
        Commodity commodity = commodityService.findById(Integer.valueOf(id));
        if (commodity==null){
            resp.sendRedirect(req.getContextPath()+"/commodity/edit");
            return;
        }
        //会话域
        HttpSession session = req.getSession();
        String error = null;
        String commodityId = req.getParameter("commodityId");
        String commodityName = req.getParameter("commodityName");
        String commodityType = req.getParameter("commodityType");
        String supply = req.getParameter("supply");
        String productionDate = req.getParameter("productionDate");
        String price = req.getParameter("price");

        //后端校验
        if (!StringUtils.hasText(commodityId)){
            error = "商品编号不可为空";
        }
        commodity.setCommodityId(commodityId);
        if (!StringUtils.hasText(commodityName)){
            error = "商品名称不可为空";
        }
        commodity.setCommodityName(commodityName);
        if (!StringUtils.hasText(commodityType)){
            error = "商品类型不可为空";
        }
        commodity.setCommodityType(commodityType);
        if (!StringUtils.hasText(supply)){
            error = "供应商不可为空";
        }
        commodity.setSupply(supply);
        if (!StringUtils.hasText(productionDate)){
            error = "出厂日期不可为空";
        }
        LocalDate productionDate1 = LocalDate.parse(productionDate,DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        commodity.setProductionDate(productionDate1);
        if (!StringUtils.hasText(price)){
            error = "价格不可为空";
        }
        if (!FormatMatch.isFloatNumber(price)){
            if (error==null){
                error = "输入价格格式不正确";
            }
        }else if(price!=""){
            Double commodityPrice = Double.parseDouble(price);
            commodity.setCommodityPrice(commodityPrice);
        }
        if (error!=null){
            session.setAttribute("error",error);
            session.setAttribute("commodity",commodity);
            resp.sendRedirect(req.getContextPath()+"/commodity/edit?id=" + id);
            return;
        }

        boolean success = commodityService.update(commodity);
        if (success){
            session.setAttribute("success","success");
            resp.sendRedirect(req.getContextPath()+"/commodity/edit");
        }else{
            session.setAttribute("error",error);
            session.setAttribute("commodity",commodity);
            resp.sendRedirect(req.getContextPath() + "/commodity/edit?id=" +id);
            return;
        }
    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) {
        String[] ids = req.getParameterValues("ids");
        Integer[] intIds = Stream.of(ids).map(Integer::valueOf).toArray(Integer[]::new);
        int rows = commodityService.deleteByIds(intIds);
        ServletUtils.renderJson(Map.of("success",true,"rows",rows),resp);
    }

    private void save(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String commodityId = req.getParameter("commodityId");
        String commodityName = req.getParameter("commodityName");
        String commodityType = req.getParameter("commodityType");
        String supply = req.getParameter("supply");
        String productionDate = req.getParameter("productionDate");
        String price = req.getParameter("price");

        Commodity commodity = new Commodity();
        //会话域
        HttpSession session = req.getSession();
        String error = null;
        //后端校验
        if (!StringUtils.hasText(commodityId)){
            error = "商品编号不可为空";

        }
        commodity.setCommodityId(commodityId);
        Commodity commodity1 = new Commodity();
        commodity1.setCommodityId(commodityId);
        boolean count = commodityService.findByCommodityId(commodity1);
        if(count){
            if (error==null){
                error = "商品编号重复";
            }
        }
        if (!StringUtils.hasText(commodityName)){
            if (error==null){
                error = "商品名称不可为空";
            }
        }
        commodity.setCommodityName(commodityName);
        if (!StringUtils.hasText(commodityType)){
            if (error==null){
                error = "商品类型不可为空";
            }
        }
        commodity.setCommodityType(commodityType);
        if (!StringUtils.hasText(supply)){
            if (error==null){
                error = "供应商不可为空";
            }
        }
        commodity.setSupply(supply);
        if (!StringUtils.hasText(productionDate)){
            if (error==null){
                error = "出厂日期不可为空";
            }
        }
        System.out.println("出厂日期:"+productionDate);
        if (productionDate!=""){
            LocalDate productionDate1 = LocalDate.parse(productionDate,DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            commodity.setProductionDate(productionDate1);
        }
        if (!StringUtils.hasText(price)){
            if (error==null){
                error = "价格不可为空";
            }
        }
        if (!FormatMatch.isFloatNumber(price)){
            if (error==null){
                error = "输入价格格式不正确";
            }
        }else if(price!=""){
            Double commodityPrice = Double.parseDouble(price);
            commodity.setCommodityPrice(commodityPrice);
        }

        if (error != null){
            session.setAttribute("error",error);
            session.setAttribute("commodity",commodity);
            resp.sendRedirect(req.getContextPath()+"/commodity/add");
            return;
        }

        boolean success = commodityService.save(commodity);
        if (success){
            session.setAttribute("success","success");
            resp.sendRedirect(req.getContextPath()+"/commodity/add");
        }else{
            session.setAttribute("error","添加商品信息失败,请联系管理员");
            session.setAttribute("commodity",commodity);
            resp.sendRedirect(req.getContextPath()+"/commodity/add");
        }

    }

    private void list(HttpServletRequest req, HttpServletResponse resp) {
        String pageNo = req.getParameter("pageNo");
        String pageSize = req.getParameter("pageSize");
        int iPageNo = 1;
        int iPageSize = 10;
        if (StringUtils.hasText(pageNo)) {
            iPageNo = Integer.parseInt(pageNo);
        }
        if (StringUtils.hasText(pageSize)) {
            iPageSize = Integer.parseInt(pageSize);
        }

        PaginateInfo pi = new PaginateInfo(iPageNo, iPageSize);

        String commodityId = req.getParameter("commodityId");
        String commodityName = req.getParameter("commodityName");
        String commodityType = req.getParameter("commodityType");
        String supply = req.getParameter("supply");
        String productionDateFrom = req.getParameter("productionDateFrom");
        String productionDateTo = req.getParameter("productionDateTo");
        String priceFrom = req.getParameter("priceFrom");
        String priceTo = req.getParameter("priceTo");
        String warehouseId = req.getParameter("warehouseId");
        CommoditySearchBean csb = new CommoditySearchBean();
        //将符合条件的值存在此对象中
        if (StringUtils.hasText(commodityId)) {
            csb.setCommodityId(commodityId);
        }
        if (StringUtils.hasText(commodityName)) {
            csb.setCommodityName(commodityName);
        }
        if (StringUtils.hasText(commodityType)) {
            csb.setCommodityType(commodityType);
        }
        if (StringUtils.hasText(supply)) {
            csb.setSupply(supply);
        }
        if (StringUtils.hasText(productionDateFrom)) {
            LocalDate dateFrom = LocalDate.parse(productionDateFrom, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            csb.setProductionDateFrom(dateFrom);
        }
        if (StringUtils.hasText(productionDateTo)) {
            LocalDate dateTo = LocalDate.parse(productionDateTo, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            csb.setProductionDateTo(dateTo);
        }
        if (StringUtils.hasText(priceFrom)) {
            Double iPriceFrom = Double.parseDouble(priceFrom);
            csb.setPriceFrom(iPriceFrom);
        }
        if (StringUtils.hasText(priceTo)) {
            Double iPriceTo = Double.parseDouble(priceTo);
            csb.setPriceTo(iPriceTo);
        }
        if (StringUtils.hasText(warehouseId)){
            csb.setWarehouseId(warehouseId);
        }

        List<Commodity> commodityList = commodityService.findAll(csb, pi);
        ServletUtils.renderJson(Map.of("pi", pi, "commodityList", commodityList), resp);
    }
}
